//1. 什么是高阶函数？(high-order)
//   函数作为参数
//   函数作为另一个函数的返回值

// 函数作为参数
// demo  forEach
{
    function lx_forEach(array, fn) {
        for (var i = 0; i < array.length; i++) {
            fn(arr[i]);
        }
    }

    let arr = [1, 2, 4, 5, 6];
    lx_forEach(arr, function (item) {
        console.log(item);
    });
}

// demo  filter
{
    function lx_filter(array, fn) {
        let results = [];
        for (var i = 0; i < array.length; i++) {
            if (fn(arr[i])) {
                results.push(arr[i]);
            }
        }
        return results;
    }

    let arr = [1, 2, 4, 5, 6];

    console.log(
        lx_filter(arr, function (item) {
            return item % 2 == 0;
        })
    );
}

// 函数作为返回值
{
    {
        // 最简单的demo;
        function base() {
            let msg = "hello hanghang";
            return function () {
                console.log(msg);
            };
        }

        // base()();
        // const return_base = base();
        // return_base();
    }

    // once 函数   只执行一次的函数
    {
        function lx_once(fn) {
            let done = false;
            return function () {
                if (!done) {
                    done = true;
                    return fn.apply(this, arguments);
                }
            };
        }

        let pay = lx_once((money) => {
            console.log("支付了" + money + "元");
            return money;
        });
        const money = pay(1000);
        console.log(money, "moneymoney");
        pay(1000);
    }
}

{
    // demo map函数
    function lx_map(array, fn) {
        let results = [];
        for (const value of array) {
            results.push(fn(value));
        }
        return results;
    }

    let arr = [1, 3, 5, 7, 9];
    let map = lx_map(arr, (item) => item * 2);
    console.log(map);
}

{
    // some 函数
    function lx_some(array, fn) {
        let flag = false;
        for (const value of array) {
            if (fn(value)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    let arr = [1, 3, 5, 6, 9];
    let some = lx_some(arr, (item) => item % 2 === 0);
    console.log(some);
}

{
    // every 函数
    function lx_every(array, fn) {
        let flag = true;
        for (const value of array) {
            if (!fn(value)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    let arr = [1, 3, 5, 7, 9];
    let every = lx_every(arr, (item) => item % 2 === 1);
    console.log(every);
}
